#!/bin/sh
# vi: ts=4 noexpandtab
#
# This is the initramfs init script
ROOTFS_LABEL="cirros-rootfs"

. /lib/cirros/shlib

mkdir -p /proc /newroot /dev /tmp /sys

mount -t devtmpfs /dev /dev
mount -t proc /proc /proc
mount -t sysfs /sys /sys

echo "6 4 1 7" >/proc/sys/kernel/printk

parse_cmdline

for x in $KC_CONSOLES; do
	[ "$x" = "$KC_CONSOLE" ] ||
		echo "further output written to $KC_CONSOLE" > "$x";
done
if [ -n "$KC_PREF_CONSOLE" ]; then
	exec >"$KC_PREF_CONSOLE" 2>&1 <"$KC_PREF_CONSOLE"
fi

read uptime cputime < /proc/uptime
iinfo "initramfs: up at $uptime"

idebug "loading modules"
/etc/init.d/load-modules start

ROOT=""
NEWROOT_MP=/newroot

rootspec="$KC_ROOT"
if [ -z "$rootspec" ]; then
	rootspec="LABEL=$ROOTFS_LABEL"
	debug 2 "using default root=$rootspec"
fi

ROOT=""
if [ "$KC_RAMDISK_ROOT" = "1" ]; then
	ROOT="ramdisk"
elif search_for_root "$rootspec" ro "$NEWROOT_MP"; then
	debug 2 "mounted root '$rootspec' from dev '${_RET_MCB_DEV}'"
	ROOT="${_RET_MCB_DEV}"
else
	debug 1 "did not find a device matching $rootspec"
fi

if [ "$KC_DEBUG" = "1" ]; then
	echo "dropping into initramfs debug shell"
	/bin/sh
fi

if [ -z "$ROOT" ]; then
	if search_for_blank "$rootspec" rw "$NEWROOT_MP"; then
		blank="${_RET_MCB_DEV}"
		# copy initramfs to new mount.
		iinfo "copying initramfs to $blank"
		items=""
		set +f
		for x in /*; do
			case "$x" in
				/dev|/proc|/newroot|/sys) : ;;
				*) items="$items $x";;
			esac
		done
		set -f
		mkdir -p "${NEWROOT_MP}/dev" "${NEWROOT_MP}/proc" "${NEWROOT_MP}/sys"
		cp -a $items "${NEWROOT_MP}/"
		cp -a "/dev/console" "$NEWROOT_MP/dev/"
		mount -o remount,ro "$NEWROOT_MP"
		ROOT="$blank"
	fi
fi

if [ -n "$ROOT" -a "$ROOT" != "ramdisk" ]; then
	cd /newroot
	mount -o move /dev ./dev
	umount /proc
	iinfo "initramfs loading root from $ROOT"
	exec switch_root /newroot "$KC_INIT" "$@"
else
	umount /proc
	[ "$ROOT" != "ramdisk" ] &&
		iinfo "initramfs did not find root, running as ramdisk" ||
		iinfo "running in ramdisk mode as requested"
	exec "$KC_INIT" "$@"
fi
failure "badness occurred in ramdisk"
